package com.mrs.runner;

import com.mrs.entity.Article;
import com.mrs.mapper.ArticleMapper;
import com.mrs.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description: ViewCountRunner
 * date: 2022/8/13 9:32
 * author: MR.孙
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //在应用启动时把博客的浏览量存到redis中
        //从mysql的文章表中获取  id   view_count
        List<Article> articleList = articleMapper.selectList(null);
        Map<String, Integer> viewCountMap = articleList.stream()
                .collect(Collectors.toMap(article1 -> article1.getId().toString(),
                        article -> article.getViewCount().intValue()));

        //存入redis
        redisCache.setCacheMap("article:viewCount",viewCountMap);
    }
}
